package com.wn.common.base

import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LiveData
import com.wn.common.ktx.viewDataBind
import com.wn.common.ktx.viewLifeCycleOwner

/**
 * @Author: wn
 * @Date: 2022/12/7 17:07
 * @Description: 抽象的公用 BaseActivity
 */
abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity {
  // 次构造函数 传递 LayoutRes  取代 abstract
  constructor() : super()
  constructor(@LayoutRes layout: Int) : super(layout)

  protected val mBinding: T by lazy {
    viewDataBind(getLayoutRes())
  }

  @LayoutRes
  protected abstract fun getLayoutRes(): Int

  // open 可以被重写  protected 可以被访问
  // 初始化视图
  protected open fun initView() {}

  // 初始化数据
  protected open fun initData() {}

  // 初始化配置
  protected open fun initConfig() {}

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mBinding.lifecycleOwner = viewLifeCycleOwner
    initView()
    initData()
    initConfig()
  }

  override fun onDestroy() {
    super.onDestroy()
    mBinding?.unbind()
  }

  /*
   * 扩展liveData的observer函数
   * */
  protected inline fun <T> LiveData<T>.observeKt(crossinline block: (T?) -> Unit) {
    observe(viewLifeCycleOwner) {
//      block(it)
      it.also(block)
    }
  }
}